package com.jinyijia.api.infrastructure;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.security.Principal;
import java.util.Map;

/**
 * @author yangrd
 * @date 2018/8/4
 **/
public final class UserInfoManager {

    public static Integer getCurrentUserId(){
        OAuth2Authentication requestingUser = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
        return getUserId(requestingUser);
    }

    public static String getCurrentUsername(){
        OAuth2Authentication requestingUser = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
        return getUsername(requestingUser);
    }

    private static Integer getUserId(Principal principal){
        return Integer.valueOf(principal.getName().replaceAll(getUsername(principal),"").replaceAll("-","").trim());
    }

    private static String getUsername(Principal principal) {
        final OAuth2Authentication authentication =(OAuth2Authentication)principal;
        String details = authentication.getUserAuthentication().getName();
        return details.split("-")[1];
    }
}
